<?php

namespace Home\Controller;
use User\Api\UserApi;
use Think\Log;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController {
    
    /**
    * 检查是否登录
    * 
    */
    protected function check_login(){
        $uid = is_login();
        if($uid){
            return $uid;
        }else{
            $this->redirect('User/login');  
        }
    }

	/* 用户中心首页 */
	public function index(){
        $uid = is_login();
        if($uid){
            $modelCic = M('CicOrder');
            $modelOrder = M('Order');
            
            //因为已经结束的也要算在金额内
            $res = $modelOrder->query("select sum(n_amt) as amt,sum(n_frozen_amt) as frozen_amt from __TABLE__ where uid=$uid and status>=2");
            if($res){
                $freeze_money = $res[0]['frozen_amt'];
                $cash_money = $res[0]['amt'];
            }else{
                $freeze_money = 0;
                $cash_money = 0;
            }
            $total_money = $freeze_money + $cash_money;
            
            //计算每天的基本奖励和环保奖励，仅在已生成保单的订单，不包括已经结束的
            $res = $modelOrder->query("select sum(day_amt) as amt,sum(day_frozen_amt) as frozen_amt from __TABLE__ where uid=$uid and status=2");
            if($res){
                $day_amt = $res[0]['amt'];
                $day_frozen_amt = $res[0]['frozen_amt'];
            }else{
                $day_amt = 0;
                $day_frozen_amt = 0;
            }
            
            //计算昨天的基本奖励和环保奖励
            $modelOrderAmt = M('OrderAmtLog');
            unset($where);
            $where['uid'] = $uid;
            $where['status'] = array('egt',2); //已支付且已经生成保单的订单,或过期的
            $subQuery = $modelOrder->field('order_id')->where($where)->select(false);
            
            $now = new \DateTime();
            $yesterday = $now->sub(new \DateInterval('P7D'));
            
            $chartLine = array();
            for($i=0;$i<7;$i++){            
                unset($where);
                $where['order_id'] = array('exp',"in $subQuery");
                $where['pdate'] = array('between',array($yesterday->format('Y-m-d'),$yesterday->format('Y-m-d 23:59:59.999999')));
                $where['isfrozen'] = 0;
                $where['ptype'] = 1;
                $resLog = $modelOrderAmt->where($where)->select();
                $arrOrder = array();
                $base_money = 0;
                foreach($resLog as $row){
                    $arrOrder[] = $row['order_id'];
                    $base_money += $row['chgval'];
                }
                $frozen_total = 0;
                $frozen_money = 0;
                if(!empty($arrOrder)){
                    array_unique($arrOrder);
                    unset($where);
                    $where['order_id'] = array('in',$arrOrder);
                    $frozen_total = $modelOrder->where($where)->sum('day_frozen_amt');
                    $where['pdate'] = array('between',array($yesterday->format('Y-m-d'),$yesterday->format('Y-m-d 23:59:59.999999')));
                    $where['isfrozen'] = 1;
                    $where['ptype'] = 1;
                    $frozen_money = $modelOrderAmt->where($where)->sum('chgval');
                }
                
                $line_data = array(
                    'jb' => $base_money,
                    'hb' => $frozen_money,
                    'hbtotal' => $frozen_total,
                    'hj' => $base_money+$frozen_money,
                    'date' => $yesterday->format('m-d'),
                );
                $chartLine[] = $line_data;
                
                $yesterday = $yesterday->add(new \DateInterval('P1D'));
            }           
            $this->assign('chartline',$chartLine);
                        
            unset($where);
            $where['uid'] = $uid;
            //$where['status'] = array('egt',2);//已支付且已经生成保单的订单,或过期的
            $count = $modelOrder->where($where)->count();
            $Page = new \Think\Page($count,10);
            $resOrder = $modelOrder->where($where)->order('order_id desc')->limit($Page->firstRow . ','. $Page->listRows)->select();

            $modelProduct = M('Product');
            foreach($resOrder as &$row){
                $product_id = $row['product_id'];
                $resProduct = $modelProduct->cache(true)->where("product_id=$product_id")->find();
                if($resProduct){
                    $row['product_name'] = $resProduct['product_name'];
                    $tableName = $resProduct['order_table'];
                    $model = M($tableName);
                    $where['corder_id'] = $row['targetid'];
                    $resCic = $model->where($where)->find();
                    if($resCic){
                        $row['c_order_no'] = $resCic['c_order_no'];
                        $dh = array();
                        $status = $resCic['status'];
                        if($status >= 1){//已支付的话，取保单号
                            $modelNo = M("{$tableName}PolicyList");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                 $dh[] = $row1['c_policy_no'];
                            }
                        }else{//未支付的话取投保单号
                            $modelNo = M("{$tableName}Dh");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                $dh[] = $row1['c_proposal_no'];
                            }
                        }
                        $row['policyno'] = $dh;
                    }
                }
            }
            $this->assign('orders',$resOrder);
            $this->assign('freeze_money',$freeze_money);
            $this->assign('cash_money',$cash_money);
            $this->assign('total_money',$total_money);
            
            $this->assign('day_amt',$day_amt);
            $this->assign('day_frozen_amt',$day_frozen_amt);
            
            $this->assign("_page",$Page->show());
            $this->assign("usermodel",1);
            $this->display();
        }else{
            $this->redirect('User/login');
        }
    }
    
    /**
    * 收益管理页面
    * 
    */
    public function profit(){
        $uid = is_login();
        if($uid){
            $modelCic = M('CicOrder');
            $modelOrder = M('Order');
            
            //因为已经结束的也要算在金额内
            $res = $modelOrder->query("select sum(n_amt) as amt,sum(n_frozen_amt) as frozen_amt from __TABLE__ where uid=$uid and status>=2");
            if($res){
                $freeze_money = $res[0]['frozen_amt'];
                $cash_money = $res[0]['amt'];
            }else{
                $freeze_money = 0;
                $cash_money = 0;
            }
            $total_money = $freeze_money + $cash_money;
                                   
            unset($where);
            $where['uid'] = $uid;
            $where['status'] = array('egt',2);//已支付且已经生成保单的订单,或过期的
            $count = $modelOrder->where($where)->count();
            $Page = new \Think\Page($count,5);
            $resOrder = $modelOrder->where($where)->order('order_id desc')->limit($Page->firstRow . ','. $Page->listRows)->select();

            $modelProduct = M('Product');
            $modelObdDayLog = M('ObdDayLog');
            foreach($resOrder as &$row){
                $product_id = $row['product_id'];
                $resProduct = $modelProduct->cache(true)->where("product_id=$product_id")->find();
                if($resProduct){
                    $row['product_name'] = $resProduct['product_name'];
                    $tableName = $resProduct['order_table'];
                    $model = M($tableName);
                    $where['corder_id'] = $row['targetid'];
                    $resCic = $model->where($where)->find();
                    if($resCic){
                        $row['c_order_no'] = $resCic['c_order_no'];
                        $dh = array();
                        $status = $resCic['status'];
                        if($status >= 1){//已支付的话，取保单号
                            $modelNo = M("{$tableName}PolicyList");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                 $dh[] = $row1['c_policy_no'];
                            }
                        }else{//未支付的话取投保单号
                            $modelNo = M("{$tableName}Dh");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                $dh[] = $row1['c_proposal_no'];
                            }
                        }
                        $row['policyno'] = $dh;
                    }
                }
                if(!empty($row['obdid'])){
                    unset($where);
                    $where['obdid'] = $row['obdid'];
                    $where['pdate'] = array('between',array($row['start_date'],$row['end_date']));
                    $where['car_status'] = 1;
                    $row['run_num'] = $modelObdDayLog->where($where)->count();
                    $where['car_status'] = 0;
                    $row['stop_num'] = $modelObdDayLog->where($where)->count();
                }
            }
            $this->assign('orders',$resOrder);
            $this->assign('freeze_money',$freeze_money);
            $this->assign('cash_money',$cash_money);
            $this->assign('total_money',$total_money);
            
            $this->assign("_page",$Page->show());
            $this->assign("usermodel",1);
            $this->display();
        }else{
            $this->redirect('User/login');
        }
    }
    
    /**
    * 订单管理页面
    * 
    * @param mixed $mobile
    */
    public function order(){
        $uid = is_login();
        if($uid){
            $modelCic = M('CicOrder');
            $modelOrder = M('Order');
            $map['uid'] = $uid;
            $map['status'] = array('egt',0);
            $count = $modelOrder->where($map)->count();
            $Page = new \Think\Page($count,5);
            $resOrder = $modelOrder->where($map)->order('order_id desc')->limit($Page->firstRow . ','. $Page->listRows)->select();

            $modelProduct = M('Product');
            $modelObdDayLog = M('ObdDayLog');
            foreach($resOrder as &$row){
                $product_id = $row['product_id'];
                $resProduct = $modelProduct->cache(true)->where("product_id=$product_id")->find();
                if($resProduct){
                    $row['product_name'] = $resProduct['product_name'];
                    $tableName = $resProduct['order_table'];
                    $model = M($tableName);
                    $where['corder_id'] = $row['targetid'];
                    $resCic = $model->where($where)->find();
                    if($resCic){
                        $row['c_order_no'] = $resCic['c_order_no'];
                        $dh = array();
                        $status = $resCic['status'];
                        if($status >= 1){//已支付的话，取保单号
                            $modelNo = M("{$tableName}PolicyList");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                 $dh[] = $row1['c_policy_no'];
                            }
                        }else{//未支付的话取投保单号
                            $modelNo = M("{$tableName}Dh");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                $dh[] = $row1['c_proposal_no'];
                            }
                        }
                        $row['policyno'] = $dh;
                    }
                }
                if(!empty($row['obdid'])){
                    unset($where);
                    $where['obdid'] = $row['obdid'];
                    $where['pdate'] = array('between',array($row['start_date'],$row['end_date']));
                    $where['car_status'] = 1;
                    $row['run_num'] = $modelObdDayLog->where($where)->count();
                    $where['car_status'] = 0;
                    $row['stop_num'] = $modelObdDayLog->where($where)->count();
                }
            }
            $this->assign('orders',$resOrder);
            $this->assign("_page",$Page->show());
            $this->assign("usermodel",1);
            $this->display();
        }else{
            $this->redirect('User/login');
        }
    }
    
    public function orderDetail(){
        $uid = is_login();
        if($uid){
            $id = I('id');
            $type = I('type');
            $modelOrder = M('Order');
            $map['uid'] = $uid;
            $map['targetid'] = $id;
            $res = $modelOrder->where($map)->find();
            if($res){//验证下是否是该用户的保单 
                $product_id = $res['product_id'];
                $modelProduct = M('Product');
                $resProduct = $modelProduct->cache(true)->where("product_id=$product_id")->find();
                if($resProduct){
                    $product_name = $resProduct['product_name'];
                    $tableName = $resProduct['order_table'];
                    
                    $model = M($tableName);
                    $where['corder_id'] = $res['targetid'];
                    $resCic = $model->where($where)->find();
                    if($resCic){
                        $dtFirst = new \DateTime($resCic['c_fst_reg_dte']);
                        $dtStart = new \DateTime($resCic['t_insrnc_bgn_tm']);
                        $dtDiff = $dtStart->diff($dtFirst);
                        $this->assign('year',$dtDiff->format('%y'));
                        $this->assign('order',$resCic);
                        $modelDetail = M("{$tableName}Detail");
                        $resCicDetail = $modelDetail->where($where)->select();
                        $dh = array();
                        $status = $resCic['status'];
                        if($status >= 1){//已支付的话，取保单号
                            $modelNo = M("{$tableName}PolicyList");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                 $dh[] = array(
                                     'business_code'=>$row1['business_code'],
                                     'c_proposal_no'=>$row1['c_policy_no'],
                                 );
                            }
                        }else{//未支付的话取投保单号
                            $modelNo = M("{$tableName}Dh");
                            $resDh = $modelNo->where($where)->select();
                            foreach($resDh as $row1){
                                 $dh[] = array(
                                     'business_code'=>$row1['business_code'],
                                     'c_proposal_no'=>$row1['c_proposal_no'],
                                 );
                            }
                        }
                        $this->assign('detail',$resCicDetail);
                        $this->assign('dh',$dh);
                    }
                }
            }
            $this->assign('nav','order');
            $this->assign("usermodel",1);
            if($type==1){
                $this->display('order_detail');
            }else{
                $this->display('order_detail_traff');
            }
        }else{
            $this->redirect('User/login');
        }
    }
    
    //获取短信验证码
    public function getVerifyMsg($mobile=''){
        if(empty($mobile)){
            $this->error('请填写手机号码！');
        }
        if(!preg_match("/^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/",$mobile)){    
            $this->error('手机号码格式不正确！');
        }

        $where['mobile'] = $mobile;
        
        $forget = I('forget');
        if(strlen($forget)>0){
            
        }else{//如果是注册的话，先判断手机号码是否被注册
            $modelUser = M('UcenterMember');
            $user = $modelUser->where($where)->find();
            if($user){
                $this->error('手机号码已经被注册');
            }
        }
        
        $vercode = session('SMS_VERCODE');
        if(!empty($vercode)){
            if(NOW_TIME - $vercode['verify_time'] < 60) {
                $this->error('60秒内只允许发送一次验证码。');
            }
        }
              
        //查找记录，是否有60秒内发过的
        $model = M('SmsLog');
        $result = $model->where($where)->order('logid desc')->limit(1)->select();
        if($result){
            $posttime = $result[0]['posttime'];
            if((strtotime('now')-strtotime($posttime))<=60){ //60秒之内只允许发送一次
                $this->error('60秒内只允许发送一次验证码。');
            }
        }
        
        $code = rand(1000,9999);
        $content ="尊敬的用户，您的验证码是：" . $code .",有效时间10分钟。";
        $ret = $this->sendSmsMsg($mobile,$content);

        $vercode = array(
            'mobile' => $mobile,
            'verify_code' => $code,
            'verify_time' => NOW_TIME,
        );
        
        session('SMS_VERCODE',$vercode);
        
        if($ret){
            $retArr = explode("\n",$ret);
            list($resptime,$respstatus) = explode(',',$retArr[0]);
            $msgid = $retArr[1];
            //记录到数据库
            $data['mobile'] = $mobile;
            $data['content'] = $content;
            $data['verifycode'] = $code;
            $data['resptime'] = $resptime;
            $data['respstatus'] = $respstatus;
            $data['msgid'] = $msgid;
            $model->add($data);
            
            $this->success('ok');
        }else{
            $this->error('短信接口异常！');
        }
    }
    
    protected function sendSmsMsg($mobile,$content){
                
        $post_data = array();
        $post_data['account'] = iconv('GB2312', 'GB2312',C('SMS_ACCOUNT'));
        $post_data['pswd'] = iconv('GB2312', 'GB2312',C('SMS_PASSWORD'));
        $post_data['mobile'] =$mobile;
        $post_data['msg']=mb_convert_encoding("$content",'UTF-8', 'auto');
        $post_data['needstatus'] = 'true';
        $url=C('SMS_URL'); 
        $o="";
        foreach ($post_data as $k=>$v)
        {
           $o.= "$k=".urlencode($v)."&";
        }
        $post_data=substr($o,0,-1);
         
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    
    //检验短信验证码
    protected function check_sms_verfiy($verify){
        $vercode = session('SMS_VERCODE');
        if(empty($vercode)) {
            return false; //短信验证码过期
        }
        // session 过期
        if(NOW_TIME - $vercode['verify_time'] > C('SMS_EXPIRE_TIME')) {
            session('SMS_VERCODE', null);
            return false; //短信验证码过期
        }
        if($verify == $vercode['verify_code']){
            session('SMS_VERCODE', null); //重置清空
            return true;
        }
        return false;
    }

	/* 注册页面 */
	public function register($mobile = '', $passwd = '', $verify = ''){
        if(!C('USER_ALLOW_REGISTER')){
            $this->error('注册已关闭');
        }
		if(IS_POST){ //注册用户
			/* 检测验证码 */
			if(!$this->check_sms_verfiy($verify)){
				$this->error('验证码输入错误！');
			}

			/* 调用注册接口注册用户 */
            $User = new UserApi;
			$uid = $User->register($mobile, $passwd, $email,$mobile);
			if(0 < $uid){ //注册成功
				//TODO: 发送验证邮件
				//$this->success('注册成功！',U('login'));
                $uid = $User->login($mobile, $passwd, 3);
                if(0 < $uid){ //UC登录成功
                    /* 登录用户 */
                    $Member = D('Member');
                    if($Member->login($uid)){ //登录用户
                        //TODO:跳转到登录前页面
                        $this->success('登录成功！',U('index'));
                    } else {
                        $this->error($Member->getError());
                    }
                }
			} else { //注册失败，显示错误信息
				$this->error($this->showRegError($uid));
			}

		} else { //显示注册表单
			$this->display();
		}
	}

	/* 登录页面 */
	public function login($mobile = '', $passwd = '', $verify = ''){
		if(IS_POST){ //登录验证
            /* 调用UC登录接口登录 */
            $user = new UserApi;
            
            if(empty($verify)){//如果不是验证码登录的话
                $uid = $user->login($mobile, $passwd, 3);
            }else{ //如果用手机号码登录的话
                $uid = $user->login($mobile, $verify, 5);
            }
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */
				$Member = D('Member');
				if($Member->login($uid)){ //登录用户
					//TODO:跳转到登录前页面
					$this->success('登录成功！',U('index'));
				} else {
					$this->error($Member->getError());
				}

			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
                    case -3: $error = '短信验证码已过期！'; break;
                    case -4: $error = '短信验证码有误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
				}
				$this->error($error);
			}

		} else { //显示登录表单
			$this->display();
		}
	}

	/* 退出登录 */
	public function logout(){
		if(is_login()){
			D('Member')->logout();
			$this->success('退出成功！', U('User/login'));
		} else {
			$this->redirect('User/login');
		}
	}

	/* 验证码，用于登录和注册 */
	public function verify(){
		$verify = new \Think\Verify();
		$verify->entry(1);
	}

	/**
	 * 获取用户注册错误信息
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '用户名长度必须在16个字符以内！'; break;
			case -2:  $error = '用户名被禁止注册！'; break;
			case -3:  $error = '用户名被占用！'; break;
			case -4:  $error = '密码长度必须在4-30个字符之间！'; break;
			case -5:  $error = '邮箱格式不正确！'; break;
			case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
			case -7:  $error = '邮箱被禁止注册！'; break;
			case -8:  $error = '邮箱被占用！'; break;
			case -9:  $error = '手机格式不正确！'; break;
			case -10: $error = '手机被禁止注册！'; break;
			case -11: $error = '手机号被占用！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}


    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function profile(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
        if ( IS_POST ) {
            //获取参数
            $uid        =   is_login();
            $password   =   I('post.old');
            $repassword = I('post.repassword');
            $data['password'] = I('post.password');
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');

            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }

            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
                $this->success('修改密码成功！');
            }else{
                $this->error($this->showRegError($res['info']));
            }
        }else{
            $this->display();
        }
    }
    
    /**
    * 获取OBD行程统计
    * 
    * @param mixed $obdid 
    * @param mixed $start
    * @param mixed $end
    */
    protected function getDayTotal($obdid,$start,$end){
        $model = M('ObdDayLog');
        //$res = $model->query("select case when (firenum>0) and ()")
    }
    
    /**
    * 获取日程记录
    * 
    */
    public function getDayLog($obdid='',$start='',$end=''){
        $uid = is_login();
        if ( $uid ) {
            $ret = array();
            if(!empty($obdid)){
                $modelLog = M('ObdDayLog');
                $map['obdid'] = $obdid;
                $map['pdate'] = array('between',array($start,$end));
                $result = $modelLog->where($map)->select();
                foreach($result as $row){
                    if($row['car_status']>0){ 
                        $color = '#CA7ED7';
                    }else{
                        $color = '#61ABDF';
                    }
                    $ret[] = array(
                        'start' => $row['pdate'],
                        'overlap' => false,
                        'rendering' => 'background',
                        'color' => $color,
                    );
                }
            }
            $this->ajaxReturn($ret);
        }else{
            $this->error( '您还没有登陆' );
        }
    }
    
    /**
    * 用户中心 提现
    * 
    */
    public function cash(){
        
    }
    
    protected function getCarInfo($modelId){
        $ret = array();
        $modelModel = M('CarModel');
        $modelSeries = M('CarSeries');
        $modelBrand = M('CarBrand');
        $resModel = $modelModel->where("model_id=$modelId")->find();
        if($resModel){
            $ret['model_name'] = $resModel['model_name'];
            $resSeries = $modelSeries->where("series_id=".$resModel['series_id'])->find();
            if($resSeries){
                $ret['series_name'] = $resSeries['series_name'];
                $resBrand = $modelBrand->where('brand_id='.$resSeries['brand_id'])->find();
                if($resBrand){
                    $ret['brand_name'] = $resBrand['brand_name'];
                }
            }
        }
        return $ret;
    }
    
    /**
    * 用户中心 -我的账号
    * 
    */
    public function prof(){
        $uid = is_login();
        if($uid){
            if(IS_POST){
                $data['realname'] = I('realname');
                $data['mobile'] = I('mobile');
                $data['sex'] = I('sex');
                $data['ident_no'] = I('ident_no');
                $data['address'] = I('address');
                $modelMember = M('Member');
                $modelMember->where("uid=$uid")->save($data);
                $resUser = $modelMember->where("uid=$uid")->find();
                $this->success($resUser);
            }else{
                $modelCic = M('CicOrder');
                $model = M('UserCar');
                $modelMember = M('Member');
                $modelObd = M('Obd');
                $resUser = $modelMember->where("uid=$uid")->find();
                
                //获取用户所属车辆
                $where['user_id'] = $uid;
                $resCars = $model->where($where)->select();
                foreach($resCars as &$row){
                    $row['info'] = $this->getCarInfo($row['series_id']);
                    
                    unset($map);
                    $map['c_lcn_no'] = $row['c_lcn_no'];
                    //$map['status'] = 1; //TODO: 条件限定是否付款
                    $resOrder = $modelCic->where($map)->order('corder_id desc')->find();//仅最新
                    if($resOrder){
                        $row['order'] = $resOrder;
                        
                        $modelCicDh = M('CicOrderDh');
                        $resCicDh = $modelCicDh->where('corder_id='.$resOrder['corder_id'])->select();
                        $row['order_dh'] = $resCicDh;
                    }
                    if(!empty($row['obd_id'])){
                        $resObd = $modelObd->where('obdid='.$row['obd_id'])->find();
                        if($resObd){
                            $resObd['modelname'] = M('ObdModel')->where("model_id=".$resObd['model_id'])->getField('modelname');
                            $row['obd'] = $resObd;
                        }
                    }
                }
                
                $this->assign('user',$resUser);
                $this->assign('cars',$resCars);
                $this->assign('nav','index');
                $this->assign("usermodel",1);
                $this->display();
            }
        }else{
            $this->redirect('User/login');
        }
    }
    
    /**
    * 地址管理
    * 
    */
    public function address(){
        $uid = is_login();
        if($uid){
            if(IS_POST){
                $model = M('UserAddress');
                $data = $model->create();
                $data['uid'] = $uid;
                $ret = $model->add($data);
                if($ret){
                    $data['aid'] = $ret;
                }
                $this->success($data);
            }
        }
    }
    
    /**
    * 收支记录
    * 
    */
    public function cashLog(){
        $uid = is_login();
        if($uid){
            $modelOrder = M('Order');
            $where['uid'] = $uid;
            $where['status'] = array('egt',2); //已支付且已经生成保单的订单,或过期的
            $subQuery = $modelOrder->field('order_id')->where($where)->select(false);
            $modelOrderAmtLog = M('OrderAmtLog');
            unset($where);
            $where['order_id'] = array('exp',"in $subQuery");
            $count = $modelOrderAmtLog->where($where)->count();
            $Page = new \Think\Page($count,20);
            $list = $modelOrderAmtLog->where($where)->order('pdate desc,pid desc')->limit($Page->firstRow . ','. $Page->listRows)->select();
            foreach($list as &$row){
                $resOrder = $modelOrder->cache(true)->where("order_id={$row['order_id']}")->find();
                if($resOrder){
                    $row['car_no'] = $resOrder['car_no'];
                }
            }
            
            $this->assign('_list',$list);
            $this->assign('_page',$Page->show());
            
            $this->display();
        }else{
            $this->redirect('User/login');  
        }
    }
    
    /**
    * 用户信息
    * 
    */
    public function info(){
        $uid = $this->check_login();
        $where['uid'] = $uid;
        $model = M('Member');
        $res = $model->where($where)->find();
        $modelAddress = M('UserAddress');
        $resAddress = $modelAddress->where($where)->select();
        $this->assign('user',$res);
        $this->assign('address',$resAddress);
        $this->display();
    }
    
    /**
    * 保存信息
    * 
    */
    public function saveinfo(){
        $uid = is_login();
        if($uid){
            $model = M('Member');
            $data=$model->create();
            $model->where("uid=$uid")->save($data);
            $res=$model->where("uid=$uid")->find();
            $res['ident_no']=hidebypass($res['ident_no'],0,14);
            $this->success($res);
        }
        else{
            echo "请先登录!";
        }
    }
    
    public function saveAddress(){
        $uid = is_login();
        if($uid){
            $aid = I('aid');
            $model = M('UserAddress');
            $data = $model->create();
            $data['uid'] = $uid;
            if(empty($aid)){//新增
                $model->add($data);
            }else{
                $model->save($data);
            }
            $where['uid'] = $uid;
            $res = $model->where($where)->select();
            $this->success($res);
        }else{
            $this->error('用户未登陆！');
        }
    }
    
    public function delAddress(){
        $uid = is_login();
        if($uid){
            $model = M('UserAddress');
            $where['aid'] = I('aid');
            $where['uid'] = $uid;
            $model->where($where)->delete();
            unset($where);
            $where['uid'] = $uid;
            $res = $model->where($where)->select();
            $this->success($res);
        }else{
            $this->error('用户未登陆！');
        }
    }
    
    /**
    * 车辆管理
    * 
    */
    public function car(){
        $uid = $this->check_login();
        
        $orderModel=M('order');
        $orderWhere['uid']=$uid;
        
        $modelCar = M('UserCar');
        $where['uid'] = $uid;
        $where['status'] = array('egt',0);
        
        $count = $modelCar->where($where)->count();
        $Page = new \Think\Page($count,5);
        $resCar = $modelCar->where($where)->order('car_id desc')->limit($Page->firstRow . ','. $Page->listRows)->select();
        foreach ($resCar as $k=>$value){
            $orderWhere['car_no'].$value.car_no;
            $resOrder=$orderModel->where($orderWhere)->find();
            if($resOrder !=null){
               $resCar[$k]['dele']=false;
            }else{
                $resCar[$k]['dele']=true;
            }
        }
        
        $ModelBrand = M('CarBrand');
        $brands = $ModelBrand->field('brand_id,brand_name,brand_alpha')->select();
        $this->assign('brands',$brands);
        
        $insurer=M('Insurer');
        $resInsurer=$insurer->where()->select();
        $this->assign('insurer',$resInsurer);
        
        $this->assign('cars',$resCar);
        $this->assign('_page',$Page->show());
        $this->display();
    }
    
    public function addCar(){
        $uid = is_login();
        if($uid){
            $modelCar=M('UserCar');
            $where['uid']=$uid;
            $date=$modelCar->create();
            if($date['c_lcn_no']==''){
                $this->error("请填写车牌号");
            }
            if ($date['c_vhl_frm']==''){
                $this->error("请填写车架号");
            }
            if ($date['c_eng_no']==''){
                $this->error("请填写发动机号");
            }
            if ($date['c_fst_reg_dte']==''){
                $this->error("请填写登记日期");
            }
            $date['brand_id']=$_POST['brand'];
            $date['series_id']=$_POST['series'];
            $date['model_id']=$_POST['model'];
            $date['insurer_id']=$_POST['insurer'];
            $modelCar->where($where)->save($date);
            $this->redirect('car');
        }else {
            $this->error("用户未登录");
        }
    }
    public function delCar(){
        $uid = is_login();
        if($uid){
            $model = M('UserCar');
            $where['car_id'] = I('car_id');
            $where['uid'] = $uid;
            $resCar=$model->where($where)->find();
            $orderModel=M('order');
            $orderWhere['uid']=$uid;
            $orderWhere['car_no']=$resCar.car_no;
            $resOrder=$orderModel->where($orderWhere)->find();
            if($resOrder !=null){
                $this->error('车辆已购险，无法删除！');
            }else{
                $data['status']=-1;
            }
            $model->where($where)->save($data);
            $this->redirect("car");
        }else{
            $this->error('用户未登陆！');
        }
        
    }
    
    /**
    * 账号安全
    * 
    */
    public function secure(){
        $uid = $this->check_login();
        if($uid){
        
        $where['uid'] = $uid;
        $model = M('Member');
        $res = $model->where($where)->find();
        $this->assign('user',$res);
        $this->display();
        }else{
            $this->error('用户未登陆！');
        }
    }
    
    /**
    * 修改手机号码
    * 
    */
    public function changePhone(){
        $uid = $this->check_login();
        if(IS_POST){//验证验证码
            $verfyCode = I('verfyCode');
            if(empty($verfyCode)){
                $this->error('请输入验证码!');
            }else{
                if($this->check_sms_verfiy($verfyCode)){
                    session('changePhone1',true);
                    $this->success('ok',U('changePhone2'));
                }else{
                    $this->error('验证码错误！');
                }
            }
        }else{
            $model = M('Member');
            $res = $model->where("uid=$uid")->find();
            $this->assign('mobile',$res['mobile']);        
            $this->display();
        }
    }
    
    /**
    * 
    * 
    */
    public function changePhone2(){
        $uid = $this->check_login();
        if(session('changePhone1')){//判断第一步是否成功
            if(IS_POST){//验证验证码
                $mobile = I('mobile');
                $verfyCode = I('verfyCode');
                if(empty($verfyCode)){
                    $this->error('请输入验证码!');
                }else{
                    //先确保填入的手机号码跟验证的相同
                    $vercode = session('SMS_VERCODE');
                    if(empty($vercode)){
                        $this->error('验证码已经过期！');
                    }
                    if($mobile != $vercode['mobile']){
                        $this->error('输入的手机号码跟发送验证码的手机号码不同！') ;
                    }
                    
                    if($this->check_sms_verfiy($verfyCode)){
                        //修改手机号码
                        $model = M('UcenterMember');
                        $where['mobile'] = $mobile;
                        $where['uid'] = array('neq',$uid);
                        //检查手机号码是否被占用
                        $res = $model->where($where)->find();
                        if($res){
                            $this->error('该手机号码已经被占用！');
                        }
                        //更新数据库中手机号码
                        unset($where);
                        $where['id'] = $uid;
                        $data['mobile'] = $mobile;
                        $model->where($where)->save($data);
                        
                        unset($where);
                        $where['uid'] = $uid;
                        $modelMember = M('Member');
                        $modelMember->where($where)->save($data);
                        
                        session('changePhone1',null);
                        $this->success('ok',U('changePhone3'));
                    }else{
                        $this->error('验证码错误！');
                    }
                }
            }else{
                $this->display();            
            }
        }else{
            $this->error('请先验证已有手机!');
        }
    }
    
    public function changePhone3(){
        $uid=$this->check_login();
        
        $model = M('Member');
        $res = $model->where("uid=$uid")->find();
        $this->assign('mobile',$res['mobile']);        
        $this->display();
    }
    
    public function chgPass(){
        $uid = $this->check_login();
        if ( IS_POST ) {
            //获取参数
            $password   =   I('oldpass');
            $repassword = I('repass');
            $data['password'] = I('newpass');
            $model=M('Member');
            $where['uid'] = $uid;
            $user=$model->where($where)->find();
            if($user['login_password_changes'] == 0){
                empty($data['password']) && $this->error('请输入登陆密码');
                empty($repassword) && $this->error('请输入确认密码');
                
            }else {
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');
            }
            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }
            $data['login_password_changes']=$user['login_password_changes']+1;
            $data['password']=think_md5(I('newpass'), C('DATA_AUTH_KEY'));
            $res = $model->where($where)->save($data);
            if($res){
                $this->redirect('User/secure');
            }else{
               $this->error('保存失败');
            }
        }else{
            $this->error('无效的请求!');
        }
    }
    
    public function chgCashPass(){
        $uid = $this->check_login();
        if ( IS_POST ) {
            $model = M('Member');
            $where['uid'] = $uid;
            $cashpass = $model->where($where)->getFieldById($uid,'cash_passwd');
            if(empty($cashpass)){
                $repassword = I('recpass');
                $newpass = I('newcpass');
                empty($newpass) && $this->error('请输入支付密码');
                empty($repassword) && $this->error('请输入确认支付密码');
                if($newpass !== $repassword){
                    $this->error('您输入的新密码与确认密码不一致');
                }
                $hash_pass = think_md5($newpass, C('DATA_AUTH_KEY'));
                $data['cash_passwd'] = $hash_pass;
                $model->where($where)->save($data);
                $this->success('设置成功！');
                
            }else{
                $password   =   I('oldcpass');
                $repassword = I('recpass');
                $newpass = I('newcpass');
                empty($password) && $this->error('请输入原密码');
                empty($newpass) && $this->error('请输入新密码');
                empty($repassword) && $this->error('请输入确认密码');
                
                if($newpass !== $repassword){
                    $this->error('您输入的新密码与确认密码不一致');
                }
                $hash_pass = think_md5($password, C('DATA_AUTH_KEY'));
                if($hash_pass != $cashpass){
                    $this->error('原有支付密码不正确！');
                }else{
                    $hash_pass = think_md5($newpass, C('DATA_AUTH_KEY'));
                    $data['cash_passwd'] = $hash_pass;
                    $model->where($where)->save($data);
                    $this->success('修改成功！');
                }
            }
            $this->error($cashpass);
        }else{
            $this->error('无效的请求!');
        }
    }
    
    public function setPass(){
        $uid = $this->check_login();
        $type = I('type');
        $model = M('Member');
        $res = $model->where("uid=$uid")->find();
        $mobile = $res['mobile'];
        if ( IS_POST ) {
            $repassword = I('repass');
            $newpass = I('newpass');
            empty($newpass) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');
            if($newpass !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }

            $verfyCode = I('verfyCode');
            if(empty($verfyCode)){
                $this->error('请输入验证码!');
            }else{
                //先确保手机号码跟验证的相同
                $vercode = session('SMS_VERCODE');
                if(empty($vercode)){
                    $this->error('验证码已经过期！');
                }
                if($mobile != $vercode['mobile']){
                    $this->error('您的手机号码跟发送验证码的手机号码不同！') ;
                }
                //
                if($this->check_sms_verfiy($verfyCode)){
                    //验证码通过
                    $hash_pass = think_md5($newpass, C('DATA_AUTH_KEY'));
                    if($type == 'cash'){
                        $where['uid'] = $uid;
                        $data['cash_passwd'] = $hash_pass;
                        $model->where($where)->save($data);
                    }else{
                        $where['id'] = $uid;
                        $data['password'] = $hash_pass;
                        M('UcenterMember')->where($where)->save($data);
                    }
                    $this->success('修改成功！');
                }else{
                    $this->error('验证码错误！');
                }
            }
        }else{
            $this->assign('mobile',$mobile);        
            $this->assign('type',$type);
            $this->display();
        }
    }

    
    /**
    * 兑换市场
    * 
    */
    public function exchange(){
        $uid = $this->check_login();
        
        //获取用户可兑换金额
        $modelOrder = M('Order');
        $where['uid'] = $uid;
        $where['status'] = array('egt',2);
        $totalMoney = $modelOrder->where($where)->sum('n_amt');
        
        //获取商品类别
        $category = $this->category('goods');

        //获取频道推荐列表 共6项
        $modelDocument = D('Document');
        $list = $modelDocument->position(2,$category['id'],6);
        //因为价格等信息在扩展表中，所以得获取详情
        foreach($list as &$row){
            $row = $modelDocument->detail($row['id']);
        }
        
        //获取兑换历史记录
        unset($where);
        $where['uid'] = $uid;
        $modelLog = M('UserExchange');
        $resLog = $modelLog->where($where)->order('eid DESC')->limit(10)->select();
        $model = M('Document');
        $status = array(-1=>'已取消',0=>'已生成',1=>'已审核',2=>'已完成');
        foreach($resLog as &$row){
            $resGood = $model->where('id='.$row['goods_id'])->cache()->find();
            if($resGood){
                $row['goods_name'] = $resGood['title'];
            }
            foreach($status as $key => $value){
                if($key == $row['status']){
                    $row['status_text'] = $value;
                    break;
                }
            }
            $row['url'] = U('User/logDetail',array('id'=>$row['eid']));
        }
         
        $this->assign('logs',$resLog);
        $this->assign('goods',$list);
        $this->assign('totalMoney',$totalMoney);
        $this->display();
    }
    
    /**
    * 支出金额
    * 
    * @param mixed $money 金额
    * @param mixed $memo 备注
    */
    protected function pay($money,$memo){
        $uid = is_login();
        if($uid){
            $where['uid'] = $uid;
            $where['status'] = array('egt',2);
            $modelOrder = M('Order');
            $modelOrderAmtLog = M('OrderAmtLog');
            M()->startTrans();
            $resOrder = $modelOrder->where($where)->select();
            foreach($resOrder as $row){
                $n_amt = $row['n_amt'];
                if($n_amt>=$money){//如果金额够用了
                    unset($data);
                    $data['order_id'] = $row['order_id'];
                    $data['pdate'] = date('Y-m-d H:i:s');
                    $data['isfrozen'] = 0;
                    $data['ptype'] = -1;
                    $data['initval'] = $n_amt;
                    $data['chgval'] = -$money;
                    $data['endval'] = $n_amt - $money;
                    $data['memo'] = $memo;
                    $modelOrderAmtLog->add($data);
                    
                    unset($data);
                    $data['n_amt'] = $n_amt - $money;
                    $modelOrder->where('order_id='.$row['order_id'])->save($data);
                    
                    break;
                }else{ //如果不够用
                    unset($data);
                    $data['order_id'] = $row['order_id'];
                    $data['pdate'] = date('Y-m-d H:i:s');
                    $data['isfrozen'] = 0;
                    $data['ptype'] = -1;
                    $data['initval'] = $n_amt;
                    $data['chgval'] = -$n_amt;
                    $data['endval'] = 0;
                    $data['memo'] = $memo ."(扣减部分 $n_amt)";
                    $modelOrderAmtLog->add($data);
                    
                    unset($data);
                    $data['n_amt'] = 0;
                    $modelOrder->where('order_id='.$row['order_id'])->save($data);
                    
                    $money -= $n_amt;                    
                }
            }
            M()->commit();
        }
    }
    
    /**
    * 开启兑换
    * 
    */
    public function buy(){
        $uid = $this->check_login();
        $goods_id = I('goods_id');
        $price = I('price');
        $extdata = I('extdata');
        $num = I('num');
        $cashpass = I('cashpass');
        
        empty($goods_id) && $this->error('商品未选择');
        empty($price) && $this->error('价格不正确');
        empty($extdata) && $this->error('信息不完整');
        empty($num) && $this->error('数量不正确');
        empty($cashpass) && $this->error('请输入支付密码');
        
        $modelMember = M('Member');
        $pass = $modelMember->where("uid=$uid")->getField('cash_passwd');
        if(think_md5($cashpass,C('DATA_AUTH_KEY'))!=$pass){
            $this->error('支付密码错误！');
        }
        
        $modelDocument = D('Document');
        $info = $modelDocument->detail($goods_id);
        if($price != $info['price']) $this->error('无效的数据递交');
        
        $amt = $price * $num;
        
        //获取用户可兑换金额
        $modelOrder = M('Order');
        $where['uid'] = $uid;
        $where['status'] = array('egt',2);
        $totalMoney = $modelOrder->where($where)->sum('n_amt');
        
        if($amt>$totalMoney) $this->error('没有足够的可用金额');
        
        $memo = "兑换{$info['title']},{$price}*{$num}={$amt}";
        $this->pay($amt,$memo);

        //记录兑换记录
        $modelLog = M('UserExchange');
        unset($data);
        $data['uid'] = $uid;
        $data['goods_id'] = $goods_id;
        $data['price'] = $price;
        $data['num'] = $num;
        $data['extdata'] = $extdata;
        $modelLog->add($data);
        
        //重新统计可用金额
        $totalMoney = $modelOrder->where($where)->sum('n_amt');
        
        //获取兑换历史记录
        unset($where);
        $where['uid'] = $uid;
        $resLog = $modelLog->where($where)->order('eid DESC')->limit(10)->select();
        $model = M('Document');
        $status = array(-1=>'已取消',0=>'已生成',1=>'已审核',2=>'已完成');
        foreach($resLog as &$row){
            $resGood = $model->where('id='.$row['goods_id'])->cache()->find();
            if($resGood){
                $row['goods_name'] = $resGood['title'];
            }
            foreach($status as $key => $value){
                if($key == $row['status']){
                    $row['status_text'] = $value;
                    break;
                }
            }
            $row['url'] = U('User/logDetail',array('id'=>$row['eid']));
        }
        
        $ret = array(
            'totalMoney'=>$totalMoney,
            'logs'=>$resLog,
        );
        $this->success($ret);
    }
    
    /* 文档分类检测 */
    private function category($id = 0){
        /* 标识正确性检测 */
        $id = $id ? $id : I('get.category', 0);
        if(empty($id)){
            $this->error('没有指定文档分类！');
        }

        /* 获取分类信息 */
        $category = D('Category')->info($id);
        if($category && 1 == $category['status']){
            switch ($category['display']) {
                case 0:
                    $this->error('该分类禁止显示！');
                    break;
                //TODO: 更多分类显示状态判断
                default:
                    return $category;
            }
        } else {
            $this->error('分类不存在或被禁用！');
        }
    }
    
    /**
    * 商城
    * 
    */
    public function goods($p=1){
        $uid = $this->check_login();
        
        //获取商品类别
        $category = $this->category('goods');
        
        $modelDocument = D('Document');
        $list = $modelDocument->page($p, $category['list_row'])->lists($category['id']);
        //因为价格等信息在扩展表中，所以得获取详情
        foreach($list as &$row){
            $row = $modelDocument->detail($row['id']);
        }
        
        $this->assign('category', $category);        
        $this->assign('goods',$list);
        $this->display();
    }
    
    /**
    * 兑换记录
    * 
    */
    public function logs(){
        $uid = $this->check_login();
        
        //获取用户可兑换金额
        $modelOrder = M('Order');
        $where['uid'] = $uid;
        $where['status'] = array('egt',2);
        $totalMoney = $modelOrder->where($where)->sum('n_amt');
        
        //获取商品类别
        $category = D('Category')->info('goods');
        if($category && 1 == $category['status']){
            switch ($category['display']) {
                case 0:
                    $this->error('该分类禁止显示！');
                    break;
                default:
                    break;
            }
        } else {
            $this->error('分类不存在或被禁用！');
        }

        //获取频道推荐列表 共6项
        $modelDocument = D('Document');
        $list = $modelDocument->position(2,$category['id'],6);
        //因为价格等信息在扩展表中，所以得获取详情
        foreach($list as &$row){
            $row = $modelDocument->detail($row['id']);
        }
        
        //获取兑换历史记录
        unset($where);
        $where['uid'] = $uid;
        $modelLog = M('UserExchange');
        $resLog = $modelLog->where($where)->order('eid DESC')->limit(10)->select();
        $model = M('Document');
        $status = array(-1=>'已取消',0=>'已生成',1=>'已审核',2=>'已完成');
        foreach($resLog as &$row){
            $resGood = $model->where('id='.$row['goods_id'])->cache()->find();
            if($resGood){
                $row['goods_name'] = $resGood['title'];
            }
            foreach($status as $key => $value){
                if($key == $row['status']){
                    $row['status_text'] = $value;
                    break;
                }
            }
            $row['url'] = U('User/logDetail',array('id'=>$row['eid']));
        }
         
        $this->assign('logs',$resLog);
        $this->assign('goods',$list);
        $this->assign('totalMoney',$totalMoney);
        $this->display();
    }
}

